package com.hongxun.budget.ui.fragment.tk;

import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.hongxun.budget.R;
import com.hongxun.budget.greendao.BPointConfigEntityDao;
import com.hongxun.budget.ui.fragment.BaseListFragment;
import com.hongxun.budget.utils.BitmapPressUtils;
import com.hongxun.budget.utils.DataUtils;
import com.hongxun.budget.utils.GreenDaoManager;
import com.hongxun.budget.utils.RecyclerViewUtils;
import com.hongxun.budget.utils.SPUtils;
import com.hongxun.budget.utils.XUtils;
import com.hongxun.entity.PhotoLabel;
import com.hongxun.greenentity.tk.BPointConfigEntity;
import com.hongxun.greenentity.tk.DPictureEntity;
import com.hongxun.net.Contants;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;
import com.previewlibrary.GPreviewBuilder;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static android.app.Activity.RESULT_OK;

/**
 * 拍照
 */

public class PhotoFragment extends BaseListFragment {

    SuperAdapter<PhotoLabel> adapter;
    List<PhotoLabel> datas = new ArrayList<>();

    int index = 0;//记录是那个label点击选择或拍照
    int indexPosition = 0;//记录那个位置

    @Override
    public void initView() {
        super.initView();
        final BPointConfigEntity b = GreenDaoManager.getInstance().getmDaoSession().getBPointConfigEntityDao().queryBuilder()
                .where(BPointConfigEntityDao.Properties.PCPoint.eq((String) SPUtils.get(context, "point_name", ""))
                        , BPointConfigEntityDao.Properties.PCType.eq(3)).unique();
        List<String> labels = Arrays.asList(b.getPCLabel().split(","));
        for (String l : labels) {
            PhotoLabel photoLabel = new PhotoLabel(context, l, "踏勘");
            datas.add(photoLabel);
        }
        adapter.setData(datas);
    }

    public void insertDB() {
        for (PhotoLabel p : datas) {
            p.save();
        }
    }

    @Override
    public SuperAdapter getAdapter() {
        return adapter = new SuperAdapter<PhotoLabel>(R.layout.content_photo_fragment) {
            @Override
            public void bindView(ViewHolder viewHolder, final PhotoLabel label, final int pos) {
                ((TextView) viewHolder.getView(R.id.label)).setText(label.getLabel());
                RecyclerView recyclerView = viewHolder.getView(R.id.list);
                recyclerView.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForHorizontal(context));
                SuperAdapter<DPictureEntity> superAdapter = new SuperAdapter<DPictureEntity>(R.layout.content_photo_label) {
                    @Override
                    public void bindView(ViewHolder viewHolder, final DPictureEntity dPictureEntity, final int i) {
                        ImageView imageView = viewHolder.getView(R.id.imageView);
                        ImageButton imageButton = viewHolder.getView(R.id.imageButton);
                        if (i == label.getEntities().size() - 1) {//设备拍照图片
                            imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                            imageButton.setVisibility(View.GONE);
                            Glide.with(context).load(R.mipmap.add_img).into(imageView);
                            imageView.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    index = pos;
                                    indexPosition = i;
                                    XUtils.imgClick(getActivity());
                                }
                            });
                        } else {
                            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                            if (new File(dPictureEntity.getPAppaddress()).exists()) {//判断图片是否本地存在
                                XUtils.loadImg(context, dPictureEntity.getPAppaddress(), imageView);
                            } else {
                                XUtils.loadImg(context, Contants.baseUrl + Contants.showPic + dPictureEntity.getPServeraddress(), imageView);
                            }
                            imageButton.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    label.getEntities().remove(i);
                                    label.getDeleteEntities().add(dPictureEntity);
                                    adapter.notifyDataSetChanged();
                                }
                            });
                            imageView.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    GPreviewBuilder.from(getActivity())
                                            .setData(DataUtils.dPicture2Image(label.getEntities()))
                                            .setCurrentIndex(i)
                                            .setSingleFling(true)//是否在黑屏区域点击返回
                                            .setDrag(false)//是否禁用图片拖拽返回
                                            .setType(GPreviewBuilder.IndicatorType.Number)//指示器类型
                                            .start();//启动
                                }
                            });
                        }
                    }
                };
                recyclerView.setAdapter(superAdapter);
                superAdapter.setData(label.getEntities());
            }
        };
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && data != null) {// 图片选择结果回调
            if (requestCode == XUtils.CHOISE_IMG) {
                List<String> pathList = data.getStringArrayListExtra("result");
                BitmapPressUtils.pressList(context, pathList, this);

            } else if (requestCode == XUtils.CAMERA_IMG) {
                String path = data.getStringExtra("result"); // 图片地址
                BitmapPressUtils.press(context, path, this);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void success(int i, JSONObject obj) {
        switch (i) {
            case 889://压缩单张图片
                String path = obj.getString("path");
                setD("相机", path);
                break;
            case 888://压缩多种图片
                String paths = obj.getString("paths");
                List<String> ps = JSON.parseArray(paths, String.class);
                for (String p : ps) {
                    setD("相册", p);
                }
                break;
        }
    }

    void setD(String resource, String path) {
        DPictureEntity d = new DPictureEntity();
        d.setPPResour(resource);
        d.setPTime(new Date());
        d.setPName(path.substring(path.lastIndexOf("/") + 1));
        d.setPAppaddress(path);
        datas.get(index).getEntities().add(indexPosition, d);
        adapter.notifyDataSetChanged();
    }

}
